<?php

namespace App\Models;

use App\Http\Controllers\Easemob;
use App\Http\Controllers\SurveysController;
use App\User;
use App\Util\Tool;
use App\Util\Url;
use Illuminate\Database\Eloquent\Model;

class AddressBook extends Model
{
    protected $table = "c_address_books";
    protected $fillable = ['user_name', 'sex', 'age', 'work_id', 'type', 'image', 'describe', 'phone', 'doctor_id','user_id'];

    public function setImageAttribute($gallery)
    {
        if (is_array($gallery)) {
            $this->attributes['image'] = json_encode($gallery);
        }
    }

    public function getImageAttribute($gallery)
    {
        return json_decode($gallery, true);
    }



    /***
     * @param $filter
     * @return bool|string
     * 签到/报道
     */
    public function add($filter)
    {
        $user = (new User())->where([['phone', '=', $filter['phone']]])->first();
        $filter['image'] = Tool::handelString($filter['image']);
        unset($filter['api_token']);
        if (empty($user)) {
            //注册账号
            //创建api_token
            $api_token = Tool::RandomToken($filter['phone']);
            //创建用户信息
            $data['name'] = $filter['user_name'];
            $data['phone'] = $filter['phone'];
            $data['age'] = $filter['age'];
            $data['sex'] = $filter['sex'];
            $data['password'] = bcrypt("123456");
            $data['api_token'] = $api_token;
            $data['created_at'] = date("Y-m-d H:i:s", time());
            $data['updated_at'] = date("Y-m-d H:i:s", time());
            $user_id = User::insertGetId($data);
            $tool = Tool::getUserNameForIm(['type' => 1, 'user_id' => $user_id]);
            (new Easemob())->createUser($tool['username'], $tool['password']);
            //注册问卷
            (new SurveysController())->register(['type' => 1, 'user_id' => $user_id]);
        } else {
            $user_id = $user->id;
        }
        $filter['user_id'] = $user_id;
        $info = $this->where([['user_id', '=', $user_id]])->first();
        if ($info) {
            $info->age = isset($filter['age']) ? $filter['age'] : $info->age;
            $info->sex = isset($filter['sex']) ? $filter['sex'] : $info->sex;
            $info->user_name = isset($filter['user_name']) ? $filter['user_name'] : $info->user_name;
            $info->phone = isset($filter['phone']) ? $filter['phone'] : $info->phone;
            $info->type = isset($filter['type']) ? $filter['type'] : $info->type;
            $info->remarks = isset($filter['remarks']) ? $filter['remarks'] : $info->remarks;
            $info->image = isset($filter['image']) ? $filter['image'] : $info->image;
            $info->describe = isset($filter['describe']) ? $filter['describe'] : $info->describe;
            $res = $info->save();
        } else {
            $res = $this->create($filter);
        }
        if ($res) {
            return true;
        } else {
            return "报道失败!";
        }
    }

    /**
     * @param $filter
     * @return mixed
     * IOS
     */
    public function getAddressBookList($filter)
    {
        $field = "id";
        $sort = "desc";
        $whereor= [];
        $where[] = ['work_id', '=', $filter['work_id']];
        if (isset($filter['type'])) {   //类型
            $where[] = ['type', '=', $filter['type']];
        }
        if (isset($filter['sex'])) {
            $where[] = ['sex', '=', $filter['sex']];
        }
        if (isset($filter['user_name'])) {
            if ($filter['user_name'] == '男' || $filter['user_name'] == '女') {
                if ($filter['user_name'] == '男') {
                    $where[] = ['sex', '=', 1];
                }
                if ($filter['user_name'] == '女') {
                    $where[] = ['sex', '=', 2];
                }
            } else {
                $where[] = ['user_name', 'like', '%' . $filter['user_name'] . '%'];
                $case_id = $this->getCaseSearch($filter['user_name']);
                if (!empty($case_id)) {
                    $whereor[] = ['work_id', '=', $filter['work_id']];
                    $whereor[] = [function ($query) use ($case_id) {
                        return $query->whereIn('case_id', $case_id);
                    }];
                }
            }
        }
        if (isset($filter['start_time']) && isset($filter['end_time'])) {
            $start = $filter['start_time'];
            $end = $filter['end_time'];
            $where[] = [function ($query) use ($start, $end) {
                $query->whereBetween('created_at', [$start, $end]);
            }];
        }
        if (isset($filter['start_age']) && isset($filter['end_age'])) {
            $start = $filter['start_age'];
            $end = $filter['end_age'];
            $where[] = [function ($query) use ($start, $end) {
                $query->whereBetween('age', [$start, $end]);
            }];
        }
        if (isset($filter['time_sort']) && $filter['time_sort'] ==1) {
            $field = "created_at";
            $sort = "desc";
        }elseif (isset($filter['time_sort']) && $filter['time_sort'] ==0){
            $field = "created_at";
            $sort = "asc";
        }
        $lable = new AddressBookRelateLabel();
        $lable_name = new AddressBookLabel();
        //标签id
        if(isset($filter['label_id'])){
            $book_ids = $lable->where([['address_book_label_id','=',$filter['label_id']]])->pluck("address_book_id");
            $where[] = [function ($query) use ($book_ids) {
                return $query->whereIn('id', $book_ids);
            }];
        }
        $host = new Url();
        $res = $this->where($where)->orWhere($whereor)->orderBy($field, $sort)->simplePaginate()->toArray();
        $newArray = [];
        if (!empty($res['data'])) {
            foreach ($res['data'] as $k => &$v) {
                if (!empty($v['image'])) {
                    foreach ($v['image'] as $kk => &$vv) {
                        $vv = $host::getHttpHost() . 'upload/' . $vv;
                    }
                }
                //查看是否打过标签
                //判断用户是否有标签
                $lable_id = $lable->where([['address_book_id', '=', $v['id']]])->orderBy("id", "desc")->pluck("address_book_label_id");
                if ($lable_id) {
                    $ws = [];
                    $ws[] = [function ($query) use ($lable_id) {
                        return $query->whereIn('id', $lable_id);
                    }];
                    $names =$lable_name->where($ws)->orderBy("is_default", "desc")->orderBy("id", "desc")->pluck("label_name");
                    if(!empty($names)){
                        $la_name = implode(',',$names->toArray());
                        $v['label_name'] =$la_name;
                    }else{
                        $v['label_name'] = "线下患者";
                    }
                   // $lable_name->where([['id', '=', $lable_id]])->value("label_name");
                }else{
                    $v['label_name'] = "线下患者";
                }
                if(empty($v['last_chat_time'])){
                    $v['last_chat_time'] = "无";
                }
                $date = date("Y/m/d",strtotime($v['created_at']));
                $newArray[$date][] = $v;
            }
        }
        $res['data'] = $newArray;
        $res['statistics'] = $this->getStatistics($filter["work_id"]);
        return $res;
    }


    /**
     * @param $filter
     * @return mixed
     * Android
     */
    public function getAddressBookListAndroid($filter)
    {
        $field = "id";
        $sort = "desc";
        $where[] = ['work_id', '=', $filter['work_id']];
        $whereor = [];
        if (isset($filter['type'])) {   //类型
            $where[] = ['type', '=', $filter['type']];
        }
        if (isset($filter['sex'])) {
            $where[] = ['sex', '=', $filter['sex']];
        }
        if (isset($filter['user_name'])) {
            if ($filter['user_name'] == '男' || $filter['user_name'] == '女') {
                if ($filter['user_name'] == '男') {
                    $where[] = ['sex', '=', 1];
                }
                if ($filter['user_name'] == '女') {
                    $where[] = ['sex', '=', 2];
                }
            } else {
                $where[] = ['user_name', 'like', '%' . $filter['user_name'] . '%'];
                $case_id = $this->getCaseSearch($filter['user_name']);
                if (!empty($case_id)) {
                    $whereor[] = ['work_id', '=', $filter['work_id']];
                    $whereor[] = [function ($query) use ($case_id) {
                        return $query->whereIn('case_id', $case_id);
                    }];
                }
            }
        }
        if (isset($filter['start_time']) && isset($filter['end_time'])) {
            $start = $filter['start_time'];
            $end = $filter['end_time'];
            $where[] = [function ($query) use ($start, $end) {
                $query->whereBetween('created_at', [$start, $end]);
            }];
        }
        if (isset($filter['start_age']) && isset($filter['end_age'])) {
            $start = $filter['start_age'];
            $end = $filter['end_age'];
            $where[] = [function ($query) use ($start, $end) {
                $query->whereBetween('age', [$start, $end]);
            }];
        }
        if (isset($filter['time_sort']) && $filter['time_sort'] ==1) {
            $field = "created_at";
            $sort = "desc";
        }elseif (isset($filter['time_sort']) && $filter['time_sort'] ==0){
            $field = "created_at";
            $sort = "asc";
        }
        $lable = new AddressBookRelateLabel();
        $lable_name = new AddressBookLabel();
        //标签id
        if(isset($filter['label_id'])){
            $book_ids = $lable->where([['address_book_label_id','=',$filter['label_id']]])->pluck("address_book_id");
            $where[] = [function ($query) use ($book_ids) {
                return $query->whereIn('id', $book_ids);
            }];
        }
        $host = new Url();
        $res = $this->where($where)->orWhere($whereor)->orderBy($field, $sort)->simplePaginate()->toArray();
        $newArray = [];
        if (!empty($res['data'])) {
            foreach ($res['data'] as $k => &$v) {
                if (!empty($v['image'])) {
                    foreach ($v['image'] as $kk => &$vv) {
                        $vv = $host::getHttpHost() . 'upload/' . $vv;
                    }
                }
                //判断用户是否有标签
//                $lable_id = (new AddressBookRelateLabel())
//                    ->join("c_address_book_labels as label","label.id",'=','c_address_book_relate_labels.address_book_label_id')
//                    ->select("label.label_name")
//                    ->where([["c_address_book_relate_labels.address_book_id","=",$v['id']],['label.is_default','=',1]])->first();
                $lable_id = $lable->where([['address_book_id', '=', $v['id']]])->orderBy("id", "desc")->pluck("address_book_label_id");
                if ($lable_id) {
                    $ws = [];
                    $ws[] = [function ($query) use ($lable_id) {
                        return $query->whereIn('id', $lable_id);
                    }];
                    $names =$lable_name->where($ws)->orderBy("is_default", "desc")->orderBy("id", "desc")->pluck("label_name");
                    if(!empty($names)){
                        $la_name = implode(',',$names->toArray());
                        $v['label_name'] =$la_name;
                    }else{
                        $v['label_name'] = "线下患者";
                    }
//                    $v['label_name'] =$lable_id->label_name;
                }else{
                    $v['label_name'] = "线下患者";
                }
                if(empty($v['last_chat_time'])){
                    $v['last_chat_time'] = "无";
                }
//                $date = date("Y/m/d",strtotime($v['created_at']));
                $newArray[] = $v;
            }
        }
        $res['data'] = $newArray;
        $res['statistics'] = $this->getStatistics($filter["work_id"]);
        return $res;
    }

    public function getCaseSearch($name)
    {
        return (new CaseBak())->where([['logs', 'like', '%' . $name . '%']])->distinct("case_id")->pluck("case_id")->toArray();
    }

    /**
     * @param $work_id
     * @return mixed
     * 统计个数
     */
    public function getStatistics($work_id)
    {
        $follow_num = $this->where([['work_id', '=', $work_id], ['type', '=', 1]])->count("id");
        $outpatient_num = $this->where([['work_id', '=', $work_id], ['type', '=', 2]])->count("id");
        $hospital_num = $this->where([['work_id', '=', $work_id], ['type', '=', 3]])->count("id");
        $data['follow_num'] = $follow_num;
        $data['outpatient_num'] = $outpatient_num;
        $data['hospital_num'] = $hospital_num;
        return $data;
    }
    
    
    /**
     * 患者详情
     */
    public function getAddressBookDetail($filter)
    {
        $res = $this->where([['id', '=', $filter['book_id']]])->first();
        $res->label = (new AddressBookRelateLabel())
            ->from("c_address_book_relate_labels as relate_label")
            ->join("c_address_book_labels as label", "relate_label.address_book_label_id", '=', 'label.id')
            ->where([['relate_label.address_book_id', '=', $res->id]])
            ->orderBy('label.is_default','desc')
            ->orderBy('label.id','desc')
            ->select(['label.label_name'])
            ->get();
        return $res->toArray();
    }
    
    /**
     * 编辑备注
     */
    public function edit($filter)
    {
        return $this->where([['id','=',$filter['book_id']]])->update(['remarks'=>$filter['remarks']]);

    }

    /***
     * @param $param
     * @throws \Exception
     * 发送问卷
     */
    public function addQuestionnaireSurvey($param)
    {
        $users = Tool::handelString($param['user_ids']);
        $doctor = Tool::getUserNameForIm(['type' => 2, 'user_id' => $param['doctor_id']]);
        $sendIm = new Easemob();
        foreach ($users as $k => $v) {
            $eas = Tool::getUserNameForIm(['type' => 1, 'user_id' => $v]);
            $survey = "点击连接跳转问卷详情\n".Url::getHttpHost()."api/surveys/handelUserCheakUrl?url={$param['url']}&type=1&user_id={$v}";
//            echo $survey."<br/>";
            $data['username'] = $eas['username'];
            $data['send_user'] = $doctor['username'];
            $data['text'] = $survey;
            $sendIm->sendTextBySdk($data);
        }
        return true;
    }
}
